# Maintainer: Martell Malone <martell malone at g mail dot com >

_realname=libwebsockets
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=4.3.5
pkgrel=1
pkgdesc="C library for websocket clients and servers (mingw-w64)"
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url='https://libwebsockets.org/'
msys2_repository_url='https://libwebsockets.org/git/libwebsockets/'
msys2_references=(
  'archlinux: libwebsockets'
)
license=('spdx:MIT')
depends=("${MINGW_PACKAGE_PREFIX}-zlib"
         "${MINGW_PACKAGE_PREFIX}-openssl")
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-ninja")
source=("https://github.com/warmcat/${_realname}/archive/v${pkgver}/${_realname}-${pkgver}.tar.gz"
        001-posix-layout.patch
        002-cmake-remove-build-hash.patch)
sha256sums=('87f99ad32803ed325fceac5327aae1f5c1b417d54ee61ad36cffc8df5f5ab276'
            '9bdfdffc74e348692b20b08881ec682ee7aa7ba65b370199dd52f99331013cdc'
            '90ad5e561980d820ffe2c84823e4da16bfb875d205cfedab221543436ab702b7')

prepare() {
  cd ${_realname}-${pkgver}
  patch -p1 -i "${srcdir}"/001-posix-layout.patch
  patch -p1 -i "${srcdir}"/002-cmake-remove-build-hash.patch
}

build() {
  mkdir -p "${srcdir}"/build-${MSYSTEM} && cd "${srcdir}"/build-${MSYSTEM}

  declare -a _extra_config
  if check_option "debug" "n"; then
    _extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    _extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
  ${MINGW_PREFIX}/bin/cmake.exe \
    -G"Ninja" \
    -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
    -DLWS_WITH_DIR=OFF \
    -DLWS_WITHOUT_DAEMONIZE=ON \
    -DLWS_WITHOUT_TESTAPPS=ON \
    ${_extra_config[@]} \
    ../${_realname}-${pkgver}

  ${MINGW_PREFIX}/bin/cmake.exe --build ./
}

package() {
  cd "${srcdir}"/build-${MSYSTEM}
  DESTDIR="${pkgdir}" ${MINGW_PREFIX}/bin/cmake.exe --install .
  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"

  local PREFIX_WIN=$(cygpath -wm ${MINGW_PREFIX})
  for _f in "${pkgdir}${MINGW_PREFIX}"/lib/cmake/${_realname}/*.cmake; do
    sed -e "s|${PREFIX_WIN}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
    sed -e "s|${MINGW_PREFIX}|\$\{_IMPORT_PREFIX\}|g" -i ${_f}
  done
}
